package com.ftdigital.primemovers_operators.util.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import com.ftdigital.primemovers_operators.R;

/**
 * Created by Curry on 2016-1-17.
 * 圆形图片
 */
public class CircleImageView extends View {

    public CircleImageView(Context context) {
        super(context);
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    Bitmap bitmap;
    BitmapShader bitmapShader;//着色器
    Paint paint;
    float scaleWidth;
    float scaleHeight;
    float canvasWidth = 200; //画布宽
    float canvasHeight = 200;//画布高
    float radius = 200;//半径

    private void init() {
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        scaleWidth = canvasWidth / bitmap.getWidth();
        scaleHeight = canvasHeight / bitmap.getHeight();
        bitmap = resizeImage(bitmap, (int) canvasWidth * 2, (int) canvasHeight * 2);
        bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);//设置着色器，选择模式为ClAMP 拉伸，另外还有REPET，MIRROR
        paint = new Paint();
        paint.setShader(bitmapShader);
    }



    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawCircle(canvasWidth, canvasHeight, radius, paint);
        super.onDraw(canvas);
    }

    /**
     *
     * @param bitmap  原bitmap
     * @param w  需改变到的宽度
     * @param h  需改变到的高度
     * @return  修改大小后的bitmap
     */
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }
}
